import requests
from fake_useragent import UserAgent
import os


def fire(page):
    url = 'https://api-tinyvideo-web.yy.com/home/tinyvideosv2'
    headers = {
        'user-agent': UserAgent().chrome
    }
    for _ in range(page+1):
        response = requests.get(url=url, headers=headers)
        data = response.json()
        data_list = data['data']['data']
        print(data_list)
        dir_name = './videos/case_06/'
        create_folder(dir_name)
        for d in data_list:
            video_title = d['username'] + '.mp4'
            video_url = d['resurl']
            video_content = requests.get(url=video_url, headers=headers).content
            with open(dir_name + video_title, mode='wb') as f:
                f.write(video_content)
                print('保存完成:', video_title)

def create_folder(dir_name):
    # 一级目录
    dir_name_first = dir_name[0:dir_name.rfind('/')+1]
    # 判断该文件夹是否存在
    if os.path.exists(dir_name_first) is False:
        # 不存在则创建
        os.mkdir(dir_name_first)
        os.mkdir(dir_name)
    elif os.path.exists(dir_name) is False:
        os.mkdir(dir_name)

if __name__ == '__main__':
    fire(1)
